<template>
  <div class="box">
    <header class="header">
      <van-nav-bar
        title="注册"
        left-arrow
        @click-left="$router.back()"
      >
      </van-nav-bar>
    </header>
    <div class="content">
      <van-field v-model="tel"  placeholder="请输入手机号码" clearable/>
      <van-button :disabled='flag' type="danger" block @click="nextStep">下一步</van-button>
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import { Field, Button, NavBar, Dialog } from 'vant'
import { docheckphone } from './../../api/user'
import { setStorage } from './../../utils/storage'
Vue.use(Field)
Vue.use(Button)
Vue.use(NavBar)
Vue.use(Dialog)
export default {
  data () {
    return {
      tel: '1881300781'
    }
  },
  computed: {
    flag () {
      return !/^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/.test(this.tel)
    }
  },
  methods: {
    nextStep () {
      docheckphone({ tel: this.tel }).then(res => {
        if (res.data.code === '10005') {
          // 该用户已被注册
          Dialog.confirm({
            title: '注册提示',
            message: '该账户已存在，是否直接登录',
            confirmButtonText: '直接登录'
          })
            .then(() => {
              this.$router.back() // 画图明确此处应该使用back
              // 可以通过本地存储，注册第一步保存手机号，到时候登录直接获取并且填充
              setStorage('tel', this.tel)
            })
            .catch(() => {
              // on cancel
            })
        } else {
          // 因为第二步需要发送短信验证码，所以通过本地存储传递
          setStorage('tel', this.tel)
          this.$router.push('/reg_step2')
        }
      })
    }
  }
}
</script>
